package nancal.mp.service

import io.kubernetes.client.custom.V1Patch
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response

/**
 * --
 * @author yuxh
 */
class K8sPatchTypeInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()

        if (request.method == "PATCH" && request.body != null) {
            var buffer = okio.Buffer();
            request.body!!.writeTo(buffer);

            var body2 = buffer.readByteString().toRequestBody(V1Patch.PATCH_FORMAT_JSON_PATCH.toMediaType())
            var request2 = request.newBuilder()
                //它会被Body里的content-type 覆盖
                .header("content-type", V1Patch.PATCH_FORMAT_JSON_PATCH)
                .patch(body2)
                .build()

            return chain.proceed(request2)
        }


        return chain.proceed(request)
    }
}